package com.shimakaze.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shimakaze.reggie.common.R;
import com.shimakaze.reggie.dto.DishDto;
import com.shimakaze.reggie.entity.Category;
import com.shimakaze.reggie.entity.Dish;
import com.shimakaze.reggie.entity.DishFlavor;
import com.shimakaze.reggie.service.CategoryService;
import com.shimakaze.reggie.service.DishFlavorService;
import com.shimakaze.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    @CacheEvict(value="dishCache",allEntries = true)
    public R<String> save(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * 菜品信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> list(int page, int pageSize, String name){
        /**
         * dish表只有菜品分类id，但前端页面需要菜品分类名称
         */
        //构造分页构造器
        Page<Dish> dishPage = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();//dishDtoPage无需参数，后面会将dishPage拷贝过去

        //条件构造器
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<Dish>();
        //添加过滤条件
        lambdaQueryWrapper.like(name != null,Dish::getName,name);
        //添加排序条件
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行分页查询，执行后dishPage就已经有结果，但没有菜品分类名称
        dishService.page(dishPage,lambdaQueryWrapper);

        //执行对象拷贝，records是dishPage的查询结果集合，但没有菜品分类名称，所以这个records不能拷贝
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");

        List<Dish> records = dishPage.getRecords();//records是所有dishPage查询结果的集合
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item,dishDto);

            //获取菜品名称
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            return dishDto; //dishDto得到dishPage的records和菜品名称
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }


    /**
     * 根据id查询菜品信息和口味信息，用于修改菜品时的数据回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }


    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    @CacheEvict(value="dishCache",allEntries = true)
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }

    /**
     * 批量删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value="dishCache",allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids){
        dishService.removeByIdWithFlavor(ids);
        return R.success("删除菜品成功");
    }

    /**
     * 批量修改菜品状态
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value="dishCache",allEntries = true)
    public R<String> updateStatus(@PathVariable int status,@RequestParam List<Long> ids){
        dishService.updateStatus(status,ids);
        return R.success("修改菜品状态成功");
    }

    /**
     * 根据条件查询菜品
     * @param dish
     * @return
     *//*
    @GetMapping("/list")
    public R<List<Dish>> list(Dish dish  *//* 传Dish通用性更高  Long categoryId*//* ){

        //条件构造器
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<Dish>();
        //添加过滤条件
        lambdaQueryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //状态为1（启售）的菜品
        lambdaQueryWrapper.eq(Dish::getStatus,1);

        //添加排序条件
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //执行查询
        List<Dish> list = dishService.list(lambdaQueryWrapper);

        return  R.success(list);
    }*/

    /**
     * 根据条件查询菜品
     * @param dish
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value="dishCache",key="#dish.categoryId + '_' + #dish.status")
    public R<List<DishDto>> list(Dish dish  /* Dish前面不用加@RequestBody是因为前端传过来的数据不是json格式，传Dish通用性更高  Long categoryId*/ ){

        //条件构造器
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<Dish>();
        //添加过滤条件
        dishLambdaQueryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //状态为1（启售）的菜品
        dishLambdaQueryWrapper.eq(Dish::getStatus,1);

        //添加排序条件
        dishLambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //执行查询
        List<Dish> list = dishService.list(dishLambdaQueryWrapper);


        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item,dishDto);

            //获取菜品名称
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //菜品id
            Long dishId = item.getId();

            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);

            dishDto.setFlavors(dishFlavorList);

            return dishDto; //dishDto得到dishPage的records和菜品名称
        }).collect(Collectors.toList());


        return  R.success(dishDtoList);
    }
}
